<template>
  <div
    v-if="visible"
    class="context-menu"
    :style="{ left: position.x + 'px', top: position.y + 'px' }"
    @click.stop
  >
    <div class="context-menu-content">
      <div
        v-for="(item, index) in items"
        :key="index"
        class="context-menu-item"
        :class="{ disabled: item.disabled }"
        @click="handleItemClick(item)"
      >
        <el-icon v-if="item.icon" class="item-icon">
          <component :is="item.icon" />
        </el-icon>
        <span class="item-label">{{ item.label }}</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'

interface MenuItem {
  label: string
  icon?: string
  disabled?: boolean
}

interface Props {
  visible: boolean
  position: { x: number; y: number }
  items: MenuItem[]
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
  (e: 'item-click', item: MenuItem): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const handleItemClick = (item: MenuItem) => {
  if (!item.disabled) {
    emit('item-click', item)
    emit('update:visible', false)
  }
}

const handleClickOutside = () => {
  emit('update:visible', false)
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped lang="scss">
.context-menu {
  position: fixed;
  z-index: 9999;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 4px 0;
  min-width: 120px;
}

.context-menu-content {
  .context-menu-item {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    cursor: pointer;
    transition: background-color 0.2s;
    
    &:hover:not(.disabled) {
      background-color: #f5f7fa;
    }
    
    &.disabled {
      color: #c0c4cc;
      cursor: not-allowed;
    }
    
    .item-icon {
      margin-right: 8px;
      font-size: 14px;
    }
    
    .item-label {
      font-size: 14px;
    }
  }
}
</style>
